﻿
//去掉字符窜的左右空格
function trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

//去掉字符窜中的所有空格
function trimAll(str) {
    return str.replace(/[ ]/g, "").replace(/[　]/g, "");
}

//去除html代码
function clearHtml(str) {
    var regEx = /<[^>]*>/g;
    return str.replace(regEx, "");
}

///验证是否为数字
function CheckNum(str) {
    if (str != "") {
        if (/\d+/.test(str))
            return true;
    }
    return false;
}

function CheckFloat(str) {
    if (str != "") {
        //if(/^[1-9]d*.d*|0.d*[1-9]d*|0?.0+|0$/.test(str))
        if (/^\d+(\.\d+)?$/.test(str))
            return true;
    }
    return false;
}

// Int
function CheckInputInt(oInput) {
    if ('' != oInput.value.replace(/\d/g, '')) {
        oInput.value = oInput.value.replace(/\D/g, '');
    }
    if (oInput.value == '')
        oInput.value = '0';
}

//Float
function CheckInputFloat(oInput) {
    if ('' != oInput.value.replace(/\d{1,}\.{0,1}\d{0,}/, '')) {
        oInput.value = oInput.value.match(/\d{1,}\.{0,1}\d{0,}/) == null ? '' : oInput.value.match(/\d{1,}\.{0,1}\d{0,}/);
    }
    if (oInput.value == '')
        oInput.value = '0';
}

//输入框提示，点击消失
function inputTextTip(inputObj, tipString) {
    //输入框对象
    this.inputObj = null;
    //提示内容
    this.tipStirng = "";

    if (inputObj) {
        this.inputObj = inputObj;
    } else {
        return;
    }
    if (tipString) {
        this.tipString = tipString;
    } else {
        return;
    }

    this.inputObj.root = this;
    this.inputObj.onblur = function() {
        if (trim(this.value) == "") {
            this.style.color = "#CCCCCC"
            this.value = this.root.tipString;
        }
    }

    this.inputObj.onfocus = function() {
        if (trim(this.value) == this.root.tipString) {
            this.style.color = "#000000";
            this.value = "";
        }
    }
}



//验证
var Validate = {
    //验证为正整数
    IsNumber: function(s) {
        var re = /^[1-9]+[0-9]*]*$/;
        if (!re.test(s)) {
            return false;
        } else {
            return true;
        }
    },

    //验证为数字
    IsNum: function(s) {
        var Number = "0123456789";
        for (i = 0; i < s.length; i++) {
            var c = s.charAt(i);
            if (Number.indexOf(c) == -1) {
                return false;
            }
        }
        return true
    },

    //判断是否为经纬度
    IsLatAndLng: function(lat, lng) {
        if (lat == "" || lat == "0" || lat <= 0 || lat == "undefined" || lat == null) {
            return false;
        }
        if (lng == "" || lng == "0" || lng <= 0 || lat == "undefined" || lat == null) {
            return false;
        }
        return true;
    },

    //验证电话
    IsTel: function(s) {
        var patrn = /^(\d){1,3}[ ]?([-]?((\d)|[ ]){0,12})+$/;
        if (!patrn.exec(s)) {
            return false;
        } else {
            return true;
        }
    },

    //验证邮箱
    IsEmail: function(s) {
        var emExp = /^([a-zA-Z0-9]+[_|\_|\.\-]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        if (s.match(emExp) == null) {
            return false;
        } else {
            return true;
        }
    },

    //验证为url
    IsUrl: function(s) {
        var pattern = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/;
        if (!pattern.exec(s)) {
            return false;
        } else {
            return true;
        }
    }
}

var objUrl = {
    path: function() {
        var url = document.location.href;
        if (url.indexOf('?') != -1) {
            return url.substr(url.indexOf('?') + 1);
        }
        else {
            return "";
        }
    },
    urlParam: function(name) {
        var url = document.location.href;
        var strParam = url.substr(url.indexOf('?') + 1).split('&');
        var param = "";
        for (i = 0; i < strParam.length; i++) {
            var parameter = strParam[i].split('=');
            switch (parameter[0].toLowerCase()) {
                case name:
                    param = parameter[1].toLowerCase();
                    break
            }
        }
        return param;
    },
    codeUrl: function() {
        return objUrl.path().replace(/&/g, '⑦').replace(/=/g, '⑥');
    },
    ecodeUrl: function() {
        return objUrl.urlParam("url").replace(/⑥/g, '=').replace(/⑦/g, '&');
    }
}

/* 屏蔽div
1.创建屏蔽
代码
ScreenDiv.createScreenDiv(zIndex,color,opacity);
参数
zIndex：屏蔽层的所在层数 (默认值：100000)
color：屏蔽层的颜色 (默认值：#959595)
opacity：屏蔽层的透明度 (默认值：0.5)
返回
无
2.删除屏蔽层
代码
ScreenDiv.destroyScreenDiv();
*/
var ScreenDiv = {
    screenDivObj: new Object(),
    createScreenDiv: function(zIndex, color, opacity) {
        var divWidth = $(document).width()-10;
        if (divWidth < 960) {
            divWidth = 950;
        }

        var divHeight = $(document).height()-10;
        var screenH = $(document).height()-10;
        if (divHeight < screenH) {
            divHeight = screenH;
        }

        if (!zIndex) {
            zIndex = 100000;
        }
        if (!color) {
            color = "#959595";
        }
        if (!opacity) {
            opacity = 0.5;
        }

        var sDiv = document.createElement("div");
        sDiv.id = "Popup_screenDiv";
        var styleStr = "position:absolute; background-color:" + color + "; opacity:" + opacity + "; filter:alpha(opacity=" + opacity * 100 + ");" +
            "left:0px; top:0px; width:" + divWidth + "px; height:" + divHeight + "px; z-index:" + zIndex + ";";
        sDiv.style.cssText = styleStr;
        ScreenDiv.screenDivObj = sDiv;
        document.body.appendChild(ScreenDiv.screenDivObj);
    },
    destroyScreenDiv: function() {
        document.body.removeChild(ScreenDiv.screenDivObj);
    },
    showScreenDiv: function() {
        ScreenDiv.screenDivObj.style.visibility = "visible";
    },
    hideScreenDiv: function() {
        ScreenDiv.screenDivObj.style.visibility = "hidden";
    }
}

/* Ajax请求 GET或者POST 一次只可发送一个请求
代码
AjaxObject.sendXml(method,url,parameter,backFun);
参数
method："GET" 或者 "POST"
url：请求的url (例如："/Ajax/getCity.aspx")
parameter：所需参数 (例如："&cid=440100&cnm=%u5E7F%u5DDE")
backFun：回调函数(使用该方法前先建立回调函数backFun(obj))
返回
请求返回后执行回调函数 backFun(obj)
*/
var AjaxObject = {
    xmlObj: new Object(),
    backFun: null,
    createXmlHttp: function() {
        if (window.ActiveXObject) {
            AjaxObject.xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
        } else if (window.XMLHttpRequest) {
            AjaxObject.xmlObj = new XMLHttpRequest();
        }
    },
    sendXml: function(method, url, parameter, backFun) {
        AjaxObject.backFun = backFun;
        AjaxObject.createXmlHttp();

        if (method == "GET") {
            var url = url + "?time=" + new Date().getTime() + parameter;
            AjaxObject.xmlObj.open("GET", url, true);
            AjaxObject.xmlObj.onreadystatechange = AjaxObject.processXmlHttp;
            AjaxObject.xmlObj.send(null);
        } else if (method == "POST") {
            var sendPara = "time=" + new Date().getTime() + parameter;
            AjaxObject.xmlObj.open("POST", url, true);
            AjaxObject.xmlObj.onreadystatechange = AjaxObject.processXmlHttp;
            AjaxObject.xmlObj.setRequestHeader("Content-Length", 3);
            AjaxObject.xmlObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            AjaxObject.xmlObj.send(sendPara);
        }
    },
    processXmlHttp: function() {
        if (AjaxObject.xmlObj.readyState == 4) {
            AjaxObject.backFun(AjaxObject.xmlObj);
        }
    }
}

/* Ajax请求 GET或者POST 一次可发送多次请求
代码 (比如两个请求)
//初始化
var ajaxObj1 = new AjaxObjecter();
var ajaxObj2 = new AjaxObjecter();

//回调函数
function back1(){
if(ajaxObj1.xmlObj.readyState == 4){
//你的代码
var obj = ajaxObj1.xmlObj.responseText;
}
}
function back2(){
if(ajaxObj2.xmlObj.readyState == 4){
//你的代码
var obj = ajaxObj2.xmlObj.responseText;
}
}
    
//发送请求
ajaxObj1.sendXml(method,url,parameter,back1);
ajaxObj2.sendXml(method,url,parameter,back2);
参数
method："GET" 或者 "POST"
url：请求的url (例如："/Ajax/getCity.aspx")
parameter：所需参数 (例如："&cid=440100&cnm=%u5E7F%u5DDE")
backFun：回调函数(使用该方法前先建立回调函数backFun())
返回
请求返回后执行回调函数 backFun()
*/
function AjaxObjecter() {
    this.xmlObj = new Object();
    this.backFun = new Object();

    this.createXmlHttp = function() {
        if (window.ActiveXObject) {
            this.xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
        } else if (window.XMLHttpRequest) {
            this.xmlObj = new XMLHttpRequest();
        }
    }

    this.sendXml = function(method, url, parameter, backFun) {
        this.backFun = backFun;
        this.createXmlHttp();

        if (method == "GET") {
            var url = url + "?time=" + new Date().getTime() + parameter;
            this.xmlObj.open("GET", url, true);
            this.xmlObj.onreadystatechange = backFun;
            this.xmlObj.send(null);
        } else if (method == "POST") {
            var sendPara = "time=" + new Date().getTime() + parameter;
            this.xmlObj.open("POST", url, true);
            this.xmlObj.onreadystatechange = backFun;
            this.xmlObj.setRequestHeader("Content-Length", 3);
            this.xmlObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            this.xmlObj.send(sendPara);
        }
    }
}

/* 分页 Ajax请求的分页
参数
thisPage：当前页码  
total：总记录数
thisPageCount：每页显示的记录数
pageCount：显示的页码数目（当前页显示在中间）
doPage：链接搜索的方法名称
返回
分页的HTML代码
*/
function getAjaxPage(thisPage, total, thisPageCount, pageCount, doPage) {
    thisPage = parseInt(thisPage);
    total = parseInt(total);
    thisPageCount = parseInt(thisPageCount);
    pageCount = parseInt(pageCount);
    if (total <= 0) {
        return "";
    } else {
        //当前页实际显示的记录数
        var count = thisPageCount;
        //总共分出来的页数
        var totalPage = 0;

        //计算出总共分出来的页数
        totalPage = Math.floor(total / thisPageCount); //向下取整
        if ((total % thisPageCount) != 0) {
            totalPage = totalPage + 1; //向上取整
        }

        //当前页不在范围之内显示到第一页
        if (thisPage > totalPage || thisPage <= 0) {
            thisPage = 1;
        }

        //计算出显示页码的起始页start
        var start = 1;
        if (totalPage <= pageCount) {
            pageCount = totalPage;
        } else {
            if (thisPage <= Math.ceil(pageCount / 2)) { //pageCount的一半向上取整
                start = 1;
            } else {
                if (thisPage > totalPage - Math.floor(pageCount / 2)) {   //pageCount的一半向下取整
                    start = totalPage - pageCount + 1;
                } else {
                    start = thisPage - Math.floor(pageCount / 2);
                }
            }
        }

        var pageHTML = "";
        pageHTML += "<div id='pagination' style='text-align:center; line-height:18px; font-size:14px; color:#0066A7;'>";

        if (totalPage > 1) {
            if (thisPage == 1) {
                pageHTML += "<span style='color:#969696;'> 首页 </span>";
                pageHTML += "<span style='color:#969696;'> 上页 </span>";
            } else {
                pageHTML += "<a href='javascript:" + doPage + "(1)' style='color:#0778B8; font-size:14px; text-decoration:none;' > 首页 </a>";
                pageHTML += "<a href='javascript:" + doPage + "(" + (thisPage - 1) + ")' style='color:#0778B8; font-size:14px; text-decoration:none;'> 上页 </a>";
            }

            for (var iPoint = start; iPoint < (start + pageCount); iPoint++) {
                if (iPoint == thisPage) {
                    pageHTML += "<strong><span style='color:#E30502;font-size:font-size:14px; font-weight:700;'> " + iPoint + " </span></strong>";
                } else {
                    pageHTML += "<a href='javascript:" + doPage + "(" + iPoint + ")' style='color:#0778B8; font-size:14px; text-decoration:none;'> " + iPoint + " </a>";
                }
            }

            if (thisPage == totalPage) {
                pageHTML += "<span style='color:#969696;'> 下页 </span>";
                pageHTML += "<span style='color:#969696;'> 末页 </span>";
            } else {
                pageHTML += "<a href='javascript:" + doPage + "(" + (thisPage + 1) + ")' style='color:#0778B8; font-size:14px; text-decoration:none;'> 下页 </a>"
                pageHTML += "<a href='javascript:" + doPage + "(" + totalPage + ")' style='color:#0778B8; font-size:14px; text-decoration:none;' > 末页 </a>";
            }
        } else {
            //pageHTML += "<span style='color:#969696;'> 首页 </span><span style='color:#969696;'> 上页 </span><strong><span style='color:#E30502;font-size:font-size:14px; font-weight:700;'> 1 </span></strong><span style='color:#969696;'> 下页 </span><span style='color:#969696;'> 末页 </span>";
        }

        pageHTML += "</div>";
        return pageHTML;
    }
}


//绑定select数据
BindSelectByListItems = function(selector, selectedVal, ListItems) {
    var selectedStr = '';
    for (var i = 0, count = ListItems.length; i < count; ++i) {
        if (ListItems[i][0] == selectedVal)
            selectedStr = ' selected="selected"';
        selector.append('<option value="' + ListItems[i][0] + '"' + selectedStr + '>' + ListItems[i][1] + '</option>');
    }
}

//获取地址参数
function GetQueryString(para) {
    var retval = "";
    var s = location.search.replace("?", "");
    if (s == "") return ""; s = s.split("&");
    for (var i = 0; i < s.length; i++)
        if (s[i].toUpperCase().indexOf(para.toUpperCase() + "=") == 0)
        retval += ((retval == "" ? "" : ", ") + s[i].substr(s[i].indexOf("=") + 1, s[i].length));
    return retval;
}

function DateAdd(date, flag, n) {
    switch (flag) {
        case 's': return new Date(Date.parse(date) + (1000 * n));
        case 'n': return new Date(Date.parse(date) + (60000 * n));
        case 'h': return new Date(Date.parse(date) + (3600000 * n));
        case 'd': return new Date(Date.parse(date) + (86400000 * n));
        case 'w': return new Date(Date.parse(date) + ((86400000 * 7) * n));
        case 'q': return new Date(date.getFullYear(), (date.getMonth()) + n * 3, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
        case 'm': return new Date(date.getFullYear(), (date.getMonth()) + n, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
        case 'y': return new Date((date.getFullYear() + n), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
    }
}

/**
* 时间对象的格式化;
*/
Date.prototype.Format = function(formatStr) {
    /*
    * eg:formatStr="YYYY-MM-dd hh:mm:ss";
    */
    var o = {
        "M+": this.getMonth() + 1,  //month
        "d+": this.getDate(),     //day
        "h+": this.getHours(),    //hour
        "m+": this.getMinutes(),  //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }

    if (/(y+)/.test(formatStr)) {
        formatStr = formatStr.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(formatStr)) {
            formatStr = formatStr.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return formatStr;
}

/**

*  where 插入内容的地方

*  el    对哪个元素操作
*  html  插入的内容

*/
function insertHtml(where, el, html) {
    where = where.toLowerCase();
    if (el.insertAdjacentHTML) {
        switch (where) {
            case "beforebegin":
                el.insertAdjacentHTML('BeforeBegin', html);
                return el.previousSibling;
            case "afterbegin":
                el.insertAdjacentHTML('AfterBegin', html);
                return el.firstChild;
            case "beforeend":
                el.insertAdjacentHTML('BeforeEnd', html);
                return el.lastChild;
            case "afterend":
                el.insertAdjacentHTML('AfterEnd', html);
                return el.nextSibling;
        }
        throw 'Illegal insertion point -> "' + where + '"';
    }
    var range = el.ownerDocument.createRange();
    var frag;
    switch (where) {
        case "beforebegin":
            range.setStartBefore(el);
            frag = range.createContextualFragment(html);
            el.parentNode.insertBefore(frag, el);
            return el.previousSibling;
        case "afterbegin":
            if (el.firstChild) {
                range.setStartBefore(el.firstChild);
                frag = range.createContextualFragment(html);
                el.insertBefore(frag, el.firstChild);
                return el.firstChild;
            } else {
                el.innerHTML = html;
                return el.firstChild;
            }
        case "beforeend":
            if (el.lastChild) {
                range.setStartAfter(el.lastChild);
                frag = range.createContextualFragment(html);
                el.appendChild(frag);
                return el.lastChild;
            } else {
                el.innerHTML = html;
                return el.lastChild;
            }
        case "afterend":
            range.setStartAfter(el);
            frag = range.createContextualFragment(html);
            el.parentNode.insertBefore(frag, el.nextSibling);
            return el.nextSibling;
    }
    throw 'Illegal insertion point -> "' + where + '"';
}


function InputOverload(o) {
    var nMaxLen = o.getAttribute ? parseInt(o.getAttribute("maxlength")) : "";
    if (o.getAttribute && o.value.length >= nMaxLen) {
        o.value = o.value.substring(0, nMaxLen);
        alert("已超出可输入长度" + nMaxLen + "！");
    }
}

//为页面加载loading DIV
function AddLoadingDiv(el,divId)
{
    var html=
    '<div id="'+ divId +'" style="display: none; position: fixed !important; position: absolute;'
    +'    top: 0; left: 0; height: 100%; width: 100%; z-index: 100006; background: #000 url(../images/load.gif) no-repeat center center;'
    +'    opacity: 0.6; filter: alpha(opacity=60); font-size: 14px; line-height: 20px;"'
    +'    onclick="javascript:document.getElementById(\'' + divId + '\').style.display=\'none\';">'
    +'    <p style="color: #fff; position: absolute; top: 50%; left: 50%;'
    +'        margin: 20px 0 0 -50px; padding: 3px 10px;" onclick="javascript:document.getElementById(\'' + divId + '\').style.display=\'none\';">'
    +'        数据加载中..'
    +'    </p>'
    +'</div>';
    insertHtml("afterEnd",el,html);
}

/** 
* 校验所有输入域是否含有特殊符号 
* 所要过滤的符号写入正则表达式中，注意，一些符号要用'\'转义. 
* 试例： 
* if(checkAllTextValid(document.forms[0])) 
* alert("表单中所有文本框通过校验！"); 
*/
function checkAllTextValid(form) {
    //记录不含引号的文本框数量 
    var resultTag = 0;
    //记录所有text文本框数量 
    var flag = 0;
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].type == "text") {
            flag = flag + 1;
            //此处填写所要过滤的特殊符号 
            //注意：修改####处的字符，其它部分不许修改. 
            //if(/^[^####]*$/.test(form.elements[i].value)) 

            if (/^[^\|"'<>]*$/.test(form.elements[i].value))
                resultTag = resultTag + 1;
            else
                form.elements[i].select();
        }
    }

    /** 
    * 如果含引号的文本框等于全部文本框的值，则校验通过 
    */
    if (resultTag == flag)
        return true;
    else {
        alert("文本框中不能含有\n\n 1 单引号: ' \n 2 双引号: \" \n 3 竖 杠: | \n 4 尖角号: < > \n\n请检查输入！");
        return false;
    }
}


function ___getPageSize() {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
        if (document.documentElement.clientWidth) {
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }
    // for small pages with total height less then height of the viewport
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }
    // for small pages with total width less then width of the viewport
    if (xScroll < windowWidth) {
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }
    arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
    return arrayPageSize;
}

function GetDivCenterObj(w,h)
{
    var cPageSize = ___getPageSize();
    var l = ( cPageSize[0] - w ) / 2+$(window).scrollLeft();
    var t = ( cPageSize[1] - h ) / 2+$(window).scrollTop();
    return new Array(l,t,w,h);
}



function OpenDiv(objId) {
    ScreenDiv.createScreenDiv();
    var center = GetDivCenterObj($("#" + objId).width(),$("#" + objId).height());
    $("#" + objId).css('left', center[0] + 'px');
    $("#" + objId).css('top', center[1] + 'px');
    $("#" + objId).show();
}

function CloseDiv(objId) {
    ScreenDiv.destroyScreenDiv();
    $("#" + objId).hide();
}